package com.qingcheng.timer;

import com.qingcheng.dao.SeckillGoodsMapper;
import com.qingcheng.pojo.seckill.SeckillGoods;
import com.qingcheng.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
public class SeckillGoodsPushTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    /**
     * 定时把商品放入redis中
     */
    @Scheduled(cron = "0/30 * * * * ?")  //每30秒执行一次
    public void loadGoodsPushRedis() {
        List<Date> dateMenus = DateUtil.getDateMenus(); //获取时间段集合
        //一个时间段就是一个大key,大key为SeckillGoods_时间字符串
        for (Date startTime : dateMenus) {
            String extName = DateUtil.date2Str(startTime);  //时间字符串
            //根据时间段查询秒杀商品
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status","1"); //审核状态为1,即通过
            criteria.andGreaterThan("stockCount",0); //剩余库存要大于0
            criteria.andGreaterThanOrEqualTo("startTime",startTime); //秒杀开始时间要大于等于当前时间的开始时间
            criteria.andLessThan("endTime",DateUtil.addDateHour(startTime,2));//秒杀结束时间要小于等于当前时间的结束时间
            //排除之前已经加载到redis中的数据
            Set keys = redisTemplate.boundHashOps("SeckillGoods_" + extName).keys();
            if(keys != null && keys.size() > 0) {
                criteria.andNotIn("id",keys);
            }
            //查询数据并放入缓存中
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);
            for (SeckillGoods seckillGood : seckillGoods) {
                redisTemplate.boundHashOps("SeckillGoods_" + extName).put(seckillGood.getId(),seckillGood);
            }
        }
    }
}
